package demo.rbac.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

  @GetMapping("/user/home")
  public String userHome() {
    return "不管是否登录，总能被访问";
  }

  @GetMapping("/user/action")
  public Map<String, Object> action() {
    Map<String, Object> info = new HashMap<>();

    Subject subject = SecurityUtils.getSubject();
    info.put("principal", subject.getPrincipal());
    boolean hasAdmin = subject.hasRole("admin");
    info.put("hasAdmin", hasAdmin);

    return info;
  }

  /**
   * 数据库里配置了用户zhangsan有admin角色，而admin角色有user:select权限
   */
  @GetMapping("/user/test")
  @RequiresPermissions("user:select")
  public String permissionTest() {
    return "已登录，且有权限user:select";
  }

  /**
   * zhangsan没有user:select2权限，不能访问
   */
  @GetMapping("/user/test2")
  @RequiresPermissions("user:select2")
  public String permissionTest2() {
    return "已登录后，且有权限user:select2";
  }
}
